package com.ruoyi.miniapp.controller;

import java.sql.Struct;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.miniapp.domain.AdmSeats;
import com.ruoyi.miniapp.domain.BasBuildings;
import com.ruoyi.miniapp.domain.BasVillage;
import com.ruoyi.miniapp.dto.CheckAdmSeatsDto;
import com.ruoyi.miniapp.dto.CheckBuildingDto;
import com.ruoyi.miniapp.dto.CheckVillageDto;
import com.ruoyi.miniapp.service.IAdmSeatsService;
import com.ruoyi.miniapp.service.IBasVillageService;
import com.ruoyi.miniapp.service.IFranSeatAgreementService;
import io.prometheus.client.Collector;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 小区信息Controller
 *
 * @author lobyliang
 * @date 2022-01-12
 */
@RestController
@Api(tags = "小区")
@RequestMapping("basVillage")
public class BasVillageController extends BaseController {
    @Autowired
    private IBasVillageService basVillageService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private IFranSeatAgreementService franSeatAgreementService;
    @Autowired
    private IAdmSeatsService iAdmSeatsService;

    /**
     * 查询小区信息列表
     */
    @RequiresPermissions("dao:village:list")
    @GetMapping("/list")
    public TableDataInfo list(BasVillage basVillage) {
        startPage();
        List<BasVillage> list = basVillageService.selectBasVillageList(basVillage);
        return getDataTable(list);
    }

    /**
     * 导出小区信息列表
     */
    @RequiresPermissions("dao:village:export")
    @Log(title = "小区信息" , businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BasVillage basVillage) throws IOException {
        List<BasVillage> list = basVillageService.selectBasVillageList(basVillage);
        ExcelUtil<BasVillage> util = new ExcelUtil<BasVillage>(BasVillage.class);
        util.exportExcel(response, list, "小区信息数据");
    }

    /**
     * 获取小区信息详细信息
     */
    @RequiresPermissions("dao:village:query")
    @GetMapping(value = "/{pkVillageCode}")
    public AjaxResult getInfo(@PathVariable("pkVillageCode") String pkVillageCode) {
        return AjaxResult.success(basVillageService.selectBasVillageByPkVillageCode(pkVillageCode));
    }

    /**
     * 新增小区信息
     */
    @RequiresPermissions("dao:village:add")
    @Log(title = "小区信息" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BasVillage basVillage) {
        return toAjax(basVillageService.insertBasVillage(basVillage));
    }

    /**
     * 修改小区信息
     */
    @RequiresPermissions("dao:village:edit")
    @Log(title = "小区信息" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BasVillage basVillage) {
        return toAjax(basVillageService.updateBasVillage(basVillage));
    }

    /**
     * 删除小区信息
     */
    @RequiresPermissions("dao:village:remove")
    @Log(title = "小区信息" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{pkVillageCodes}")
    public AjaxResult remove(@PathVariable String[] pkVillageCodes) {
        return toAjax(basVillageService.deleteBasVillageByPkVillageCodes(pkVillageCodes));
    }


    @ApiOperation("获取小区列表信息")
    @GetMapping("getVillageList")
    public R getVillageList(Page<BasVillage> page, String name) {
        String unionId = SecurityUtils.getUnionId();
        basVillageService.listPage(page, name);
        Map<String, Map> map = redisService.getCacheMap("check_adm_seats_" + unionId);
        List<String> hasLocked = franSeatAgreementService.findOccupyAdmSeatCodes();
        if (map != null) {
            page.getRecords().forEach(r -> {
                CheckVillageDto dto = BeanUtil.toBean(map.get(r.getPkVillageCode()), CheckVillageDto.class);
                if (dto != null) {
                    r.setHasCheckNum(dto.getSeatsNum());
                }
                List<String> asCodes = iAdmSeatsService.villageAdmSeatsCodes(r.getPkVillageCode());
                if(asCodes.size()>0){
                    List<String> list = new ArrayList<>();
                    list.addAll(asCodes);
                    asCodes.removeAll(hasLocked);
                    list.removeAll(asCodes);
                    if(r.getNotInstallCount() > 0){
                        r.setNotInstallCount(r.getNotInstallCount() - list.size());
                    }
                }
            });
        }
        return R.ok(page);
    }

    @ApiOperation("小区信息")
    @GetMapping("getVillageInfo")
    public R getVillageInfo(String code) {
        String unionId = SecurityUtils.getUnionId();
        BasVillage village = basVillageService.getBasVillageInfo(code);
        Map<String, Map> map = redisService.getCacheMap("check_adm_seats_" + unionId);
        List<String> hasLocked = franSeatAgreementService.findOccupyAdmSeatCodes();
        if (StrUtil.isNotEmpty(unionId)) {
            village.getBuildingsList().forEach(b -> {
                b.getAdmSeatsList().forEach(s -> {
                    if (hasLocked.contains(s.getPkSeatCode()) && StrUtil.isEmpty(s.getFkFranchiseeId())) {
                        s.setFkFranchiseeId("0000");
                    }
                    if(s.getIsEmpty() == 0 && StrUtil.isEmpty(s.getFkFranchiseeId())){
                        s.setFkFranchiseeId("0000");
                    }
                });
            });

            if (map.containsKey(code)) { //有小区
                CheckVillageDto dto = BeanUtil.toBean(map.get(code), CheckVillageDto.class);
                for (BasBuildings b : village.getBuildingsList()) {
                    if (dto.getBuildingList() != null) {
                        for (CheckBuildingDto cb : dto.getBuildingList()) {
                            if (b.getPkBuildingCode().equals(cb.getBuildingCode())) {
                                if (cb.getAdmSeatsList() != null && cb.getAdmSeatsList().size() > 0) {
                                    List<String> seatsCodes = cb.getAdmSeatsList().stream().map(CheckAdmSeatsDto::getAdmSeatsCode).collect(Collectors.toList());
                                    for (AdmSeats seats : b.getAdmSeatsList()) {
                                        if (seatsCodes.contains(seats.getPkSeatCode())) {
                                            seats.setHasCheck(1);
                                        }
                                        if (hasLocked.contains(seats.getPkSeatCode())) {
                                            seats.setFkFranchiseeId("0000");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return R.ok(village);
    }

    @ApiOperation("选择机位")
    @PostMapping("checkAdmSeats")
    public R checkAdmSeats(@RequestBody CheckVillageDto dto) {
        String unionId = SecurityUtils.getUnionId();
        if (dto.getBuildingList() == null || dto.getBuildingList().size() == 0) {
            Map<String, Object> map = redisService.getCacheMap("check_adm_seats_" + unionId);
            if (map == null) {
                map = new HashMap<String, Object>();
            }
            map.remove(dto.getVillageCode());
            if (map.keySet().size() == 0) {
                redisService.deleteObject("check_adm_seats_" + unionId);
            } else {
                redisService.setCacheMap("check_adm_seats_" + unionId, map);
            }
            return R.ok();
        }
        int num = 0;
        for (CheckBuildingDto b : dto.getBuildingList()) {
            num += b.getAdmSeatsList().size();
        }
        dto.setSeatsNum(num);
        Map<String, Object> map = redisService.getCacheMap("check_adm_seats_" + unionId);
        if (map == null) {
            map = new HashMap<String, Object>();
        }
        map.put(dto.getVillageCode(), BeanUtil.beanToMap(dto));
        redisService.setCacheMap("check_adm_seats_" + unionId, map);
        return R.ok();
    }

    @ApiOperation("获取已选择机位信息")
    @GetMapping("getHasCheckAdmSeatsInfo")
    public R getHasCheckAdmSeatsInfo() {
        String unionId = SecurityUtils.getUnionId();
        Map<String, Object> map = redisService.getCacheMap("check_adm_seats_" + unionId);
        Integer seatsNum = 0;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            CheckVillageDto dto = BeanUtil.toBean(entry.getValue(), CheckVillageDto.class);
            seatsNum = seatsNum + dto.getSeatsNum();
        }
        Map rtMap = new HashMap();
        rtMap.put("villageNum" , map.keySet().size());
        rtMap.put("seatsNum" , seatsNum);
        if (map.keySet().size() > 0) {
            rtMap.put("allVillage" , basVillageService.findByCodes(new ArrayList<>(map.keySet())));
        }
        rtMap.put("checkVillageInfo" , map);
        return R.ok(rtMap);
    }

    @GetMapping("maintainerVillages")
    public R<List<BasVillage>> maintainerVillages(Long maintainerId){
        return R.ok(basVillageService.maintainerVillages(maintainerId));
    }

}
